package com.chaos.gateway.config.filter;


import com.chaos.gateway.config.properties.ResourceServerProperties;
import com.chaos.framework.model.constant.SecurityConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * @author Jacky
 */
@Component
@Order(-1)
@Slf4j
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {
    private final PathMatcher pathMatcher = new AntPathMatcher();
    private final String authPath = "/auth/oauth2/**";

    @Resource
    private ResourceServerProperties resourceServerProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        // log.info("path：{}", uri.getPath());
        if (pathMatcher.match(authPath, uri.getPath())) {
            return chain.filter(exchange);
        }
        List<String> ignoreUrls = resourceServerProperties.getIgnoreUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                request = exchange.getRequest().mutate().header(SecurityConstants.AUTHORIZATION_KEY, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }

}

